package com.zjyd.douyangauth.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zjyd.douyangcommoncore.entity.DyUsers;
import com.zjyd.douyangcommoncore.result.Result;
import com.zjyd.douyangcommoncore.service.DyUsersService;
import com.zjyd.douyangcommoncore.vo.DyUsersRegisterByPasswordVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *  注册
 */
@Slf4j
@RestController
@Tag(name = "注册")
@RequestMapping("/douyang/auth/register")
public class RegisterController {

    @Autowired
    private DyUsersService dyUsersService;

    /**
     * 用户名密码注册
     */
    @Operation(summary = "用户名密码注册")
    @PostMapping("/usernamePassword")
    public Result usernamePassword(@Valid @RequestBody DyUsersRegisterByPasswordVO dyUsersRegisterByPasswordVO){
        DyUsers dyUsers = new DyUsers();
        BeanUtils.copyProperties(dyUsersRegisterByPasswordVO, dyUsers);

        //查询用户名是否已存在
        QueryWrapper<DyUsers> queryWrapper = new QueryWrapper<DyUsers>()
                .eq("username", dyUsers.getUsername());
        DyUsers one = dyUsersService.getOne(queryWrapper);
        if (one != null){
            return Result.error("用户名已存在");
        }


        //随机生成一个随机字符串(盐值)
        String salt = RandomUtil.randomString(20);
        log.info("盐值为：{}",salt);
        // 创建一个md5对象
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        String passwordSalt = md5.digestHex(dyUsers.getPassword()+salt);

        //SecureUtil.md5 对密码进行加密
        log.info("加密后的密码为：{}",passwordSalt);
        dyUsers.setPassword(passwordSalt);
        dyUsers.setSalt(salt);
        dyUsersService.save(dyUsers);
        return Result.success("用户名密码注册");
    }

}
